package test.http.core.it;

import blue.base.core.common.ErrorCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author Jin Zheng
 * @since 1.0 2021-08-24
 */
public class UserService {
	private static Logger logger = LoggerFactory.getLogger(UserService.class);

	private Map<String, User> userMap = new ConcurrentHashMap<>();
	private Map<String, String> tokenUserMap = new ConcurrentHashMap<>();
	private Map<String, String> userTokenMap = new ConcurrentHashMap<>();

	public static final UserService INSTANCE = new UserService();
	private UserService() {
	}

	public void reg(User user) {
		if (userMap.containsKey(user.getUsername()))
			throw ErrorCode.EXISTS.newException(user.getUsername());

		userMap.put(user.getUsername(), user);
	}

	public String login(User user) {
		User tmp = userMap.get(user.getUsername());
		if (tmp == null || !tmp.getPassword().equals(user.getPassword()))
			throw ErrorCode.LOGIN_FAILURE.newException();

		String token = UUID.randomUUID().toString();
		String oldToken = userTokenMap.get(user.getUsername());
		if (oldToken != null && !oldToken.isEmpty()) {
			tokenUserMap.remove(oldToken);
			logger.info("remove old token for user: {}, {}", user.getUsername(), oldToken);
		}
		tokenUserMap.put(token, user.getUsername());
		userTokenMap.put(user.getUsername(), token);
		logger.info("put new token for user: {}, {}", user.getUsername(), token);

		return token;
	}

	public User getByToken(String token) {
		String username = tokenUserMap.get(token);
		if (username == null || username.isEmpty())
			return null;

		return userMap.get(username);
	}

	public Collection<User> listAll() {
		return userMap.values();
	}

	public void clear() {
		userMap.clear();
		tokenUserMap.clear();
		userTokenMap.clear();
	}

}
